#!/usr/local/bin/python2.7
import os

from rstwriter import *
from constants import *

class RstMaker(object):
    def __init__(self):
        
        self._sub_systems = {}
        self._components = []
        self._problems = {}

        self._rstwriter = RstWriter()
        self._rstwriter.dst_dir = Constants.rst_index_dir
        self._rstwriter.overwrite = True
        self._dst_dir = Constants.rst_index_dir
        self._problems_filename = 'problems.rst'
        self._comps_filename = 'comps.rst'

        self._sys_names = {}
        self._comps_by_sys = {}
        self._rsts = {}
        self._buildSysNames()

    def _buildSysNames(self):
        self._sys_names[0] = 'No primary sys number'
        self._sys_names[1] = 'Primary Coolant System'
        self._sys_names[2] = 'Secondary Coolant System'
        self._sys_names[3] = 'Primary Bypass Demineralizer System'
        self._sys_names[4] = 'Utility Coolant Water System'
        self._sys_names[5] = 'Liquid Waste System'
        self._sys_names[6] = 'Compressed Air System'
        self._sys_names[7] = 'High Pressure Demineralized Water System'
        self._sys_names[8] = 'Low Pressure Demineralized Water System'
        self._sys_names[9] = 'Gland Seal Water System'
        self._sys_names[10] = 'Raw,Fire, and Domestic Water Systems'
        self._sys_names[11] = 'Chemical Treatment System'
        self._sys_names[12] = 'Diesel Generator System'
        self._sys_names[13] = 'Vessel Vent System'
        self._sys_names[14] = 'High Pressure Air System'
        self._sys_names[15] = 'Health Physics Instrumentation System'
        self._sys_names[16] = 'Plant Electrical Distribution System'
        self._sys_names[17] = 'N16 Power Monitoring System'
        self._sys_names[18] = 'Canal System'
        self._sys_names[19] = 'Heating and Ventilation Systems'
        self._sys_names[20] = 'Radiation Monitoring Systems'
        self._sys_names[21] = 'Reactor Building'
        self._sys_names[22] = 'ATR Computer Systems (RDAS, DCS, and CDS)'
        self._sys_names[23] = 'Reactor Shutdown System'
        self._sys_names[24] = 'Reactor Vessel Internals'
        self._sys_names[25] = 'PCS Recycle System'
        self._sys_names[26] = 'Control Room Systems'

        for key in self._sys_names.keys():
            self._comps_by_sys[key] = []

    def addComponent(self, comp):
        prim_sysnum = self._getSysNum(self, comp)
        self._comps_by_sys[prim_sysnum].append(comp)

    def addComponents(self, comps):
        for comp in comps:
            prim_sysnum = self._getSysNum(comp)
            self._comps_by_sys[prim_sysnum].append(comp)

    def _getSysNum(self, comp):
        sys_ids = comp.getValue('gen', 'SystemNumber')
        
        try:
            prim_sysnum = int(sys_ids[0])
        except:
            prim_sysnum = 0

        return prim_sysnum

    def getProblems(self):
        return self._problems
    def setProblems(self, val):
        self._problems = val
    problems = property(getProblems, setProblems)

    def generateRstIndex(self):
        self._buildSysIndices()

        self._buildIntro()
        self._buildProblems()
        self._buildComps()
        self._buildTocTree()
        self._buildConc()

        self._writeIndex()

    def _buildSysIndices(self):
        for sys_num, group in self._comps_by_sys.items():
            rst = ''
            header = str(sys_num) + ' - ' + self._sys_names[sys_num]
            underline = '-' * len(header)
            rst += '\n\n' + header + '\n' + underline + '\n\n'

            rst += '.. toctree::\n'
            rst += '   :maxdepth: 1\n'

            for comp in group:
                rst = self._buildCompRst(comp, rst)

            self._rsts[sys_num] = rst

    def _buildCompRst(self, comp, sys_rst):
        self._rstwriter.component = comp

        self._rstwriter.saveFile()
        try:
            pass
        except Exception as err:
            print err

        sys_rst += '\n   ' + os.path.basename(self._rstwriter.dst)

        return sys_rst

    def _buildProblems(self):
        top_rst = ''
        header = 'Problems'
        underline = '=' * len(header)
        top_rst += '\n\n' + header + '\n' + underline + '\n\n'
        top_rst += '.. toctree::\n'
        top_rst += '   :maxdepth: 1\n\n'

        for key, group in self._problems.items():
            rst = ''
            header = key + ' (' + str(len(group)) + ' items)'
            underline = '=' * len(header)
            rst += '\n\n' + header + '\n' + underline + '\n\n'

            rst += '.. toctree::\n'
            rst += '   :maxdepth: 1\n'

            for comp in group:
                rst += '\n   ' + comp.name + '.rst'

            filename = 'prob-' + key + '.rst'
            full_path = os.path.join(self._dst_dir, filename)
            with open(full_path, 'w') as myfile:
                myfile.write(rst.encode('UTF-8'))

            top_rst += '   ' + filename + '\n'

        full_path = os.path.join(self._dst_dir, self._problems_filename)
        with open(full_path, 'w') as myfile:
            myfile.write(top_rst.encode('UTF-8'))

    def _buildComps(self):
        rst_tot = \
"""
Plant Components
================

.. toctree::
   :maxdepth: 1

"""
        for key, rst in self._rsts.items():
            rst += '\n'
            filename = 'sys-' + str(key) + '.rst'
            full_path = os.path.join(self._dst_dir, filename)
            with open(full_path, 'w') as myfile:
                myfile.write(rst.encode('UTF-8'))

            rst_tot += '   ' + filename + '\n'

        full_path = os.path.join(self._dst_dir, self._comps_filename)
        with open(full_path, 'w') as myfile:
            myfile.write(rst_tot.encode('UTF-8'))

    def _buildTocTree(self):
        self._rst += '   ' + self._problems_filename + '\n'
        self._rst += '   ' + self._comps_filename + '\n'

    def _writeIndex(self):
        full_path = os.path.join(self._dst_dir, 'index.rst')
        with open(full_path, 'w') as myfile:
            myfile.write(self._rst.encode('UTF-8'))

    def _buildIntro(self):
        self._rst = \
"""
.. ATR Config Management documentation master file, created by
   sphinx-quickstart on Mon Jun 06 13:23:35 2011.

Welcome to the ATR Configuration Management Index
=================================================

Contents:

.. toctree::
   :maxdepth: 2

"""
        

    def _buildConc(self):
        self._rst += \
"""


Indices and tables
==================

* :ref:`genindex`
* :ref:`search`

"""

